<template>
  <a-modal
    :visible="open"
    title="资产出库"
    width="60%"
    @ok="handlePreSubmit"
    @cancel="onClose"
  >
    <div>
      <a-space>
        客户
        <a-select
          ref="select"
          v-model:value="assetSo.clientId"
          style="width: 120px;"
          @change="handleChangeClient"
          allowClear
        >
          <a-select-option
            v-for="item in clientList"
            :key="item.id"
            :value="item.id"
          >{{ item.clientName }}
          </a-select-option
          >
        </a-select>
        楼层
        <a-select
          ref="select"
          v-model:value="assetSo.floorId"
          style="width: 120px;"
          @change="handleChangeFloor"
          allowClear
        >
          <a-select-option
            v-for="item in floorList"
            :key="item.id"
            :value="item.id"
          >{{ item.floor }}
          </a-select-option
          >
        </a-select>
        库房
        <a-select
          ref="select"
          v-model:value="assetSo.positionId"
          style="width: 120px;"
          allowClear
        >
          <a-select-option
            v-for="item in positionList"
            :key="item.id"
            :value="item.id"
          >{{ item.position }}
          </a-select-option
          >
        </a-select>
        <a-button @click="reload" type="primary">查询</a-button>
      </a-space>
    </div>
    <a-table
      :loading="loading"
      size="middle"
      :dataSource="dataSource"
      :columns="columns"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange,onSelectAll:onSelectAll }"
      rowKey="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'inventoryStatus'">

          <a-tag v-if="record.inventoryStatus == 1" color="blue">在库</a-tag>
          <a-tag v-else-if="record.inventoryStatus == 2" color="orange">多盘</a-tag>
          <a-tag v-else color="red">未盘点</a-tag>
        </template>
        <template v-if="column.key === 'operation'">
          <a-button
            class="button-interval"
            type="link"
            size="small"
            @click="handleDetail(record)"
          >
            查看
          </a-button>
          <a-button
            class="button-interval"
            type="link"
            size="small"
            @click="handleDelete(record)"
          >
            删除
          </a-button>
        </template>
      </template>
    </a-table>
  </a-modal>
  <a-modal v-model:open="openSubmit" title="出库确认" @ok="handleSubmit">
    <p>本次出库将出库 {{ selectedRowKeys.length }} 条记录</p>
    <div style="display: flex;align-items:center;margin-top:8px">出库原因：
      <a-input style="flex:1" v-model:value="reason"></a-input>
    </div>

  </a-modal>
</template>
<script lang="ts" setup>
import {
  computed,
  defineProps,
  onMounted,
  ref,
  unref,
  defineEmits,
  reactive,
  type PropType
} from "vue";
import {
  type AssetBo,
  type AssetPageVo, type AssetSo,
  type ClientVo,
  type FloorVo, lifecycleApi, type LifecycleVo,
  listClientApi, listFloorApi, listPositionApi, outboundSubmitApi,
  pageAssetApi, type PositionVo, submitTransferApi
} from "#/api";
import {message, Modal} from "ant-design-vue";
import {SearchOutlined} from "@ant-design/icons-vue";
import {useUserStore} from "@vben/stores";

const userStore = useUserStore();
const props = defineProps({
  open: {
    type: Boolean,
    required: true,
    default: false,
  }
});
const emit = defineEmits(['close'])

const dataSource = ref<AssetPageVo[]>([]);
const clientList = ref<ClientVo[]>([]);
const floorList = ref<FloorVo[]>([]);
const positionList = ref<PositionVo[]>([]);
const loading = ref<boolean>(false);
const selectedRowKeys = ref<string[]>([])
const isSelectAll = ref(false)
const openSubmit = ref(false)
const reason = ref<string>('')


const ADMIN_LIST = ['ADMIN', 'SUPER_ADMIN']

const onClose = () => {
  console.log('close')
  emit('close')
}


const assetSo = ref({
  keyword: '',
  clientId: '',
  floorId: '',
  positionId: '',
})
const pageParam = computed(() => ({
  query: assetSo.value,
  current: 1,
  size: 99999,
}));

const isAdmin = computed(() => {
  return userStore.userRoles.some(element => ADMIN_LIST.includes(element));
})

// const selectRowCount = computed(()=>{
//   return selectedRowKeys.value.length
// })
const columns = [
  {
    title: '资产编码',
    dataIndex: 'assetCode',
    key: 'assetCode',
    width: 180,
    align: 'center',
  },
  {
    title: '资产名称',
    dataIndex: 'assetName',
    key: 'contractName',
    align: 'center',
  },
  {
    title: 'EPC芯片码',
    dataIndex: 'assetEpc',
    key: 'assetEpc',
    width: 240,
    align: 'center',
  },
  {
    title: '所属客户',
    dataIndex: 'clientName',
    key: 'clientName',
    width: 200,
    align: 'center',
  },
  {
    title: '资产位置',
    dataIndex: 'address',
    key: 'address',
    width: 240,
    align: 'center',
  },
];

onMounted(() => {

  list();
  listClient();
})

const handleTransferSubmit = async () => {
  console.log('targetKeys', targetKeys.value)
  transferBo.assets.push(...targetKeys.value)
  console.log('transferBo', transferBo)
  const res = await submitTransferApi(transferBo)
  message.success("调拨成功")
  emit('close')
}

async function list() {
  loading.value = true;
  const res = await pageAssetApi(unref(pageParam));
  dataSource.value = res.records;
  // pagination.value.total = Number(res.total);
  // pagination.value.current = Number(res.current);
  loading.value = false;
}

const reload = () => {
  // pagination.value.current = 1
  list()
}

async function listClient() {
  clientList.value = await listClientApi();
  assetSo.value.clientId = clientList.value[0]?.id
  if (assetSo.value.clientId) {
    loadFloor()
  }
}

const loadFloor = async () => {
  assetSo.value.floorId = undefined
  assetSo.value.positionId = undefined
  const res = await listFloorApi({clientId: assetSo.value.clientId});
  console.log('loadFloor', res)
  floorList.value = res;
}
const loadPosition = async () => {
  console.log('here', assetSo.value.floorId)
  const floor = floorList.value.filter(s => s.id == assetSo.value.floorId);
  console.log('floor', floor)
  assetSo.value.positionId = undefined
  if (floor.length == 1) {
    const res = await listPositionApi({
      clientId: assetSo.value.clientId,
      floorName: floor[0].floor
    });
    positionList.value = res;
  }

}

const onSelectChange = (record, selected, selectedRows, nativeEvent) => {
  // selectedRowKeys.value = keys;
  console.log('record', record)
  console.log('selected', selected)
  console.log('selectedRows', selectedRows)
  console.log('nativeEvent', nativeEvent)
  if (isSelectAll.value) {
    isSelectAll.value = false
    return
  }

  let tempSelectedKeys = selectedRowKeys.value;
  let deletedKeys = []
  let addKeys = []
  selectedRowKeys.value.forEach(s => {
    if (record.indexOf(s) == -1) {
      deletedKeys.push(s)
    }
  })

  selectedRowKeys.value = selectedRowKeys.value.filter(v => !deletedKeys.includes(v));

  record.forEach(s => {
    if (selectedRowKeys.value.indexOf(s) == -1) {
      addKeys.push(s)
    }
  })
  selectedRowKeys.value.push(...addKeys)

  // record.forEach(s => {
  //   if (selectedRowKeys.value.indexOf(s) > -1) {
  //
  //   } else {
  //     selectedRowKeys.value.push(s)
  //   }
  // })
  console.log('selectedRowKeys', selectedRowKeys.value)
}


const handleChangeClient = async () => {
  if (!assetSo.value.clientId) {
    floorList.value = []
    positionList.value = []
    assetSo.value.floorId = undefined
    assetSo.value.positionId = undefined
    return
  }
  loadFloor()
}
const handleChangeFloor = async () => {
  if (!assetSo.value.floorId) {
    positionList.value = []
    assetSo.value.positionId = undefined
    return
  }
  await loadPosition();

}

function handleTableChange(page) {
  pagination.value.current = page.current;
  list();
}

const onSelectAll = (selected, selectedRows, changeRows) => {
  isSelectAll.value = true
  console.log('onSelectAll', selected, selectedRows, changeRows)
  if (selected) {
    console.log('selected all true')
    const allId = dataSource.value.map(s => s.id);
    console.log(allId)
    selectedRowKeys.value = allId;
    console.log(selectedRowKeys.value)
  } else {
    console.log('selected all false')
    selectedRowKeys.value = [];
  }
}

const handlePreSubmit = () => {
  if (selectedRowKeys.value.length == 0) {
    message.warn('请先勾选要出库的资产')
    return
  }
  openSubmit.value = true
}

const handleSubmit = async () => {
  const body = {
    reason: reason.value,
    assets: selectedRowKeys.value
  }
  await outboundSubmitApi(body)
  openSubmit.value = false
  onClose()
}
</script>
